import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import log from '@/utils/console'

const APP_KEY = '10001'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['X-Appkey'] = APP_KEY
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
      log.primary('\n================================>')
      log.success('请求接口:' + config.baseURL + config.url)
      log.success('请求方式:' + config.method.toUpperCase())
      log.success('请求参数:' + JSON.stringify(config.data !== undefined ? config.data : ''))
    }
    return config
  },
  error => {
    // do something with request error
    log.danger(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code !== 20000) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === -20008 || res.code === -20015 || res.code === -20018) {
        // to re-login
        MessageBox.confirm('请重新登录', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      log.success('响应结果：' + JSON.stringify(res.data))
      log.primary('<================================\n')
      return res.data
    }
  },
  error => {
    log.danger('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
